package com.program.facesigninsystem.controller;

import cn.yueshutong.springbootstartercurrentlimiting.annotation.CurrentLimiter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.program.facesigninsystem.entity.*;
import com.program.facesigninsystem.iteration.dto.AddSigninLinkParam;
import com.program.facesigninsystem.iteration.entity.RewardPointsEntity;
import com.program.facesigninsystem.iteration.entity.SigninactivityEntity;
import com.program.facesigninsystem.iteration.entity.SigninclassEntity;
import com.program.facesigninsystem.iteration.mapper.RewardPointsMapper;
import com.program.facesigninsystem.iteration.mapper.SigninactivityMapper;
import com.program.facesigninsystem.iteration.mapper.SigninclassMapper;
import com.program.facesigninsystem.service.*;
import com.program.facesigninsystem.util.ChangeDate;
import com.program.facesigninsystem.util.GetInfoUtil;
import com.program.facesigninsystem.util.PageUtil;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import com.program.facesigninsystem.enums.RabbitEnum;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

import static com.program.facesigninsystem.util.ScanCodeUtil.decodeCode;
import static com.program.facesigninsystem.util.ScanCodeUtil.encodeCode;


/***
 * @author Mapler
 */
@CrossOrigin
@RestController
@RequestMapping(value = "/act")
public class SignInActivityController {
    private static Logger log = Logger.getLogger(SignInActivityController.class.toString());
    private static final int LOCATION = 522;
    private static final int CODE = 829;
    @Resource
    IRewardService iRewardService;
    @Resource
    ISignInActivityService iSignInActivityService;
    @Autowired
    ISignInRecordService iSignInRecordService;
    @Autowired
    SignInClassService signInClassService;
    @Resource
    IUserInfoService iUserInfoService;
    @Resource
    IClassesService iClassesService;
    @Resource
    ISignInCourseService iSignInCourseService;
    @Resource
    RewardPointsMapper rewardPointsMapper;
    @Resource
    SigninclassMapper signinclassMapper;
    @Resource
    SigninactivityMapper signinactivityMapper;

    @Resource
    RedisTemplate redisTemplate;


    @ApiOperation("创建第一次签到")
    @RequestMapping(value = "/pubfirstAct",method = RequestMethod.POST)
    public ResponseModel pubfirstActivity(@RequestBody JSONObject act){
        final int rewardPerTime = 30;
        final int dayMaxReward = 100;
        try{
            String actId = GetInfoUtil.getId();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentTime = dateFormat.format(System.currentTimeMillis());
            String cid;
            String ccid = GetInfoUtil.getId();
            try{ cid=act.getString("cid");}
            catch (Exception e){cid="";}
            iSignInCourseService.addNewCourse(ccid,act.getString("name"), act.getString("week"),act.getString("section"),act.getString("tid"),currentTime,cid,act.getString("year"),act.getString("semester"));
            if(!act.containsKey("signStopType")){
                iSignInActivityService.addNewActivity(actId, act.getString("title"), currentTime, act.getString("actType"),
                        act.getString("caption"), cid, act.getString("tid"),-1,act.getInt("signInType"),act.getInt("actCircle"),act.getString("originactId"),ccid);
            }else{
                iSignInActivityService.addNewActivity(actId, act.getString("title"), currentTime, act.getString("actType"),
                        act.getString("caption"), cid, act.getString("tid"),act.getInt("signStopType"),
                        act.getInt("signInType"),act.getInt("actCircle"),act.getString("originactId"),ccid);
            }

            iUserInfoService.updateIssued(act.getString("tid"));
            Object[] listSession = act.getJSONArray("listSession").toArray();
            for (Object aListSession : listSession) {
                String lid = GetInfoUtil.getId();
                JSONObject temp = JSONObject.fromObject(aListSession);
//                iSignInActivityService.addNewLink(lid, temp.getInt("linkType"), temp.getString("duration"),
//                        temp.getString("startTime"), temp.getString("endTime"), temp.getInt("status"),
//                        actId,temp.getDouble("location_x"), temp.getDouble("location_y"), temp.getDouble("range"));
                iSignInActivityService.addNewLink(lid, temp.getInt("linkType"), temp.getString("duration"),
                        null, null, temp.getInt("status"),
                        actId,temp.getDouble("location_x"), temp.getDouble("location_y"), temp.getDouble("range"));
                if(act.getInt("signStopType")==1){
                    int code = startLinkActForever(lid);
                    if(code == 0){
                        return new ResponseModel(144,"激活手动签到失败");
                    }
                }
            }
            String uid = act.getString("tid");

            RewardPointsEntity rewardPointsEntity = rewardPointsMapper.selectOne(new QueryWrapper<RewardPointsEntity>().eq("uid", uid));
            String lastGainDay;
            String currentDay = dateFormat.format(System.currentTimeMillis()).substring(0,10);
            //先判断列表是否有记录，没有则新增记录
            if(rewardPointsEntity == null){
                iRewardService.addNewRewards(uid, 0, 0, 0, 1,
                        currentDay, rewardPerTime, rewardPerTime);
            }else{
                //有则更新记录
                int limitFromRecordA = rewardPointsEntity.getLimitFromRecordA();
                int limitFromRecordB = rewardPointsEntity.getLimitFromRecordB();
                int limitFromRecordC = rewardPointsEntity.getLimitFromRecordC();
                int limitFromRecordActivity = rewardPointsEntity.getLimitFromActivity();
                lastGainDay = rewardPointsEntity.getLastGainDay();
                int rewardPoints = rewardPointsEntity.getRewardPoints();
                log.info("lastGainDay:" + lastGainDay);

                if(!lastGainDay.equals(currentDay)) {
                    //如果上次获取积分的日期不等于今天，则直接新增一条记录，并将上次获取积分的日期改为今天
                    iRewardService.updateRewards(uid, 0, 0, 0, 1, currentDay, rewardPoints+rewardPerTime, rewardPerTime);
                }else {
                    //如果上次获取积分的日期等于今天

//                    if(dayMaxReward<rewards.getDay_reward()) {
                    if(dayMaxReward<rewardPointsEntity.getDayReward()) {
                        return new ResponseModel(200,"创建成功","今日获取总积分已达上限");
                    }
                    //判断是不是今天第一次获取
                    else if (limitFromRecordActivity == 0) {
                        iRewardService.updateRewards(uid, limitFromRecordA, limitFromRecordB, limitFromRecordC, 1, currentDay, rewardPoints+rewardPerTime, rewardPointsEntity.getDayReward()+rewardPerTime);
                    }else{
                        return new ResponseModel(200,"创建成功","今日创建活动获取积分次数已达上限");
                    }
                }
            }
            return new ResponseModel(200,"创建成功","积分 +30");
        }catch (Exception e){
            log.log(Level.SEVERE,"Error parsing date",e);
            return new ResponseModel(168,"创建失败");
        }
    }

    @RequestMapping(value = "/pubNewAct",method = RequestMethod.POST)
    public ResponseModel addNewActivity(@RequestBody JSONObject act){
        final int rewardPerTime = 30;
        final int dayMaxReward = 100;
        try{
            String actId = GetInfoUtil.getId();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentTime = dateFormat.format(System.currentTimeMillis());
            String cid;
            String ccid = "无";
            if(act.containsKey("ccid")){
                ccid=act.getString("ccid");
            }
            try{ cid=act.getString("cid");}
            catch (Exception e){cid="";}
            if(!act.containsKey("signStopType")){
                iSignInActivityService.addNewActivity(actId, act.getString("title"), currentTime, act.getString("actType"),
                        act.getString("caption"), cid, act.getString("tid"),-1,act.getInt("signInType"),act.getInt("actCircle"),act.getString("originactId"),ccid);
            }else{
                iSignInActivityService.addNewActivity(actId, act.getString("title"), currentTime, act.getString("actType"),
                        act.getString("caption"), cid, act.getString("tid"),act.getInt("signStopType"),
                        act.getInt("signInType"),act.getInt("actCircle"),act.getString("originactId"),ccid);
            }

            iUserInfoService.updateIssued(act.getString("tid"));
            Object[] listSession = act.getJSONArray("listSession").toArray();
            for (Object aListSession : listSession) {
                String lid = GetInfoUtil.getId();
                JSONObject temp = JSONObject.fromObject(aListSession);
//                iSignInActivityService.addNewLink(lid, temp.getInt("linkType"), temp.getString("duration"),
//                        temp.getString("startTime"), temp.getString("endTime"), temp.getInt("status"),
//                        actId,temp.getDouble("location_x"), temp.getDouble("location_y"), temp.getDouble("range"));
                iSignInActivityService.addNewLink(lid, temp.getInt("linkType"), temp.getString("duration"),
                        null, null, temp.getInt("status"),
                        actId,temp.getDouble("location_x"), temp.getDouble("location_y"), temp.getDouble("range"));
                if(act.getInt("signStopType")==1){
                    int code = startLinkActForever(lid);
                    if(code == 0){
                        return new ResponseModel(144,"激活手动签到失败");
                    }
                }
            }
            String uid = act.getString("tid");

            RewardPointsEntity rewardPointsEntity = rewardPointsMapper.selectOne(new QueryWrapper<RewardPointsEntity>().eq("uid", uid));
            String lastGainDay;
            String currentDay = dateFormat.format(System.currentTimeMillis()).substring(0,10);
            //先判断列表是否有记录，没有则新增记录
            if(rewardPointsEntity == null){
                iRewardService.addNewRewards(uid, 0, 0, 0, 1,
                        currentDay, rewardPerTime, rewardPerTime);
            }else{
                //有则更新记录
                int limitFromRecordA = rewardPointsEntity.getLimitFromRecordA();
                int limitFromRecordB = rewardPointsEntity.getLimitFromRecordB();
                int limitFromRecordC = rewardPointsEntity.getLimitFromRecordC();
                int limitFromRecordActivity = rewardPointsEntity.getLimitFromActivity();
                lastGainDay = rewardPointsEntity.getLastGainDay();
                int rewardPoints = rewardPointsEntity.getRewardPoints();
                log.info("lastGainDay:" + lastGainDay);

                if(!lastGainDay.equals(currentDay)) {
                    //如果上次获取积分的日期不等于今天，则直接新增一条记录，并将上次获取积分的日期改为今天
                    iRewardService.updateRewards(uid, 0, 0, 0, 1, currentDay, rewardPoints+rewardPerTime, rewardPerTime);
                }else {
                    //如果上次获取积分的日期等于今天

//                    if(dayMaxReward<rewards.getDay_reward()) {
                    if(dayMaxReward<rewardPointsEntity.getDayReward()) {
                        return new ResponseModel(200,"创建成功","今日获取总积分已达上限");
                    }
                    //判断是不是今天第一次获取
                    else if (limitFromRecordActivity == 0) {
                        iRewardService.updateRewards(uid, limitFromRecordA, limitFromRecordB, limitFromRecordC, 1, currentDay, rewardPoints+rewardPerTime, rewardPointsEntity.getDayReward()+rewardPerTime);
                    }else{
                        return new ResponseModel(200,"创建成功","今日创建活动获取积分次数已达上限");
                    }
                }
            }
            return new ResponseModel(200,"创建成功","积分 +30");
        }catch (Exception e){
            log.log(Level.SEVERE,"Error parsing date",e);
            return new ResponseModel(168,"创建失败");
        }
    }

    @RequestMapping(value = "/findActByTid",method = RequestMethod.GET)
    @CurrentLimiter(QPS=5)
    public  void findActByTid(
            HttpServletResponse resp,
            @RequestParam("tid")String tid,
            @RequestParam(value = "createTime",required = false,defaultValue = "%")String createTime,
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "20") int pageSize
    ){
        Object[] activityList = iSignInActivityService.selectActivityByTid(tid,createTime);

        List<JSONObject> data = new ArrayList<>();
        try{
            for (Object anActivityList : activityList) {
                JSONObject act = JSONObject.fromObject(anActivityList);
//                String cid = act.getString("cid");
//                if ((cid != null) && (!"".equals(cid))) {
//                    Classes classes = iClassesService.selectClass(cid);
//                    if (classes != null) {
//                        act.accumulate("className", classes.getName());
//                    } else {
//                        act.accumulate("className", "");
//                    }
//                }
                String cid = act.getString("cid");

                if ((cid != null) && (!"".equals(cid))) {
                    SigninclassEntity signinclassEntity = signinclassMapper.selectById(Integer.parseInt(cid));
                    if (signinclassEntity != null) {
                        act.accumulate("className", signinclassEntity.getName());
                    } else {
                        act.accumulate("className", "");
                    }
                }
                act.remove("tid");
                Object[] linkList = iSignInActivityService.selectLinkByActId(act.getString("actId"));
                List<JSONObject> temp = new ArrayList<>();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String currentTime = dateFormat.format(System.currentTimeMillis());
                for (Object aLinkList : linkList) {
                    JSONObject link = JSONObject.fromObject(aLinkList);
                    link.remove("actId");
                    if (link.getString("endTime") != null && !link.getString("endTime").equals("") &&currentTime.compareTo(link.getString("endTime")) > 0 && (!link.getString("endTime").equals(link.getString("startTime")))) {
                        link.put("status", 2);
                    }
                    temp.add(link);
                }
                act.accumulate("links", temp);
                data.add(act);
            }
            JSONObject data1 = PageUtil.wrap(data,"data", pageSize, pageNum);
            resp.setCharacterEncoding("utf-8");
            /*得到输出流*/
            PrintWriter respWriter = resp.getWriter();
            /*将JSON格式的对象toString()后发送*/
            respWriter.append(data1.toString());
        }catch (Exception e){
            log.log(Level.SEVERE,"Error parsing date",e);
        }
    }
    @ApiOperation("修改签到重复情况")
    @RequestMapping(value="/updateActivityCircle",method = RequestMethod.GET)
    public  ResponseModel updateActivityCircle(@RequestParam("actid")String actId,@RequestParam("actCircle")int actCircle){
        try {
            iSignInActivityService.updateActivityCircleByID(actId,actCircle);
            return new ResponseModel(200,"取消重复成功");
        }catch(Exception e){
            return new ResponseModel(144,"取消重复失败");
        }
    }
    @RequestMapping(value = "/deleteActivity",method = RequestMethod.GET)
    public  ResponseModel deleteActivity(@RequestParam("actid")String actId){
        try {
            iSignInActivityService.deleteActivityByID(actId);
            return new ResponseModel(200,"删除成功");
        }catch(Exception e){
            return new ResponseModel(144,"删除失败");
        }
    }

    @RequestMapping(value = "/updateLinkStatus",method = RequestMethod.GET)
    public  ResponseModel updateLinkStatus(@RequestParam("lid")String lid,@RequestParam(value = "status")int status,@RequestParam("duration")String duration){
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String startTime = dateFormat.format(System.currentTimeMillis());
            long tmpDuration = Long.parseLong(duration);
            tmpDuration = tmpDuration*60*1000;
            String endTime = dateFormat.format(System.currentTimeMillis()+tmpDuration);
            iSignInActivityService.updateLinkStatus(lid,status,startTime,endTime);
            SignInLink signInLink = iSignInActivityService.selectLinkByLid(lid);

            //同时生成激活码
            String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            StringBuilder code = new StringBuilder();
            for(int i=0;i<6;i++)
            {
                char c = str.charAt(new Random().nextInt(str.length()));
                code.append(c);
            }
            redisTemplate.opsForValue().set(lid + "-code", code.toString(), tmpDuration/1000, TimeUnit.SECONDS);

            if(signInLink.getRangement() == 0&&signInLink.getLocation_x() == 0&&signInLink.getLocation_y() == 0) {
                return new ResponseModel(200,"激活成功",LOCATION);
            }
            return new ResponseModel(200,"激活成功",CODE);
        }catch(Exception e){
            log.log(Level.SEVERE,"Error parsing date",e);
            return new ResponseModel(144,"激活失败");
        }
    }

    public int startLinkActForever(@RequestParam("lid")String lid){
        try {
            //SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //String startTime = dateFormat.format(System.currentTimeMillis());
            iSignInActivityService.updateLinkStatus(lid,1,null,null);
            iSignInActivityService.updateLinkDuration(lid, -1);
            //SignInLink signInLink = iSignInActivityService.selectLinkByLid(lid);

            //同时生成激活码
            String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            StringBuilder code = new StringBuilder();
            for(int i=0;i<6;i++)
            {
                char c = str.charAt(new Random().nextInt(str.length()));
                code.append(c);
            }
            redisTemplate.opsForValue().set(lid + "-code", code.toString());

            return 1;
            /*if(signInLink.getRangement() == 0&&signInLink.getLocation_x() == 0&&signInLink.getLocation_y() == 0) {
                return new ResponseModel(200,"激活成功",LOCATION);
            }
            return new ResponseModel(200,"激活成功",CODE);*/
        }catch(Exception e){
            log.log(Level.SEVERE,"Error parsing date",e);
            return 0;
            // return new ResponseModel(144,"激活失败");
        }
    }

    @RequestMapping(value = "/updateCode",method = RequestMethod.GET)
    @CurrentLimiter(QPS=5)
    public  ResponseModel updateCode(@RequestParam("lid")String lid){
        try{
            return new ResponseModel(200,"二维码获取成功",encodeCode(lid));
        }catch (Exception e){
            return new ResponseModel(143,"二维码获取失败");
        }
    }

    //TODO **把uid删了
    @RequestMapping(value = "/scanCode",method = RequestMethod.GET)
    @CurrentLimiter(QPS=5)
    public  ResponseModel scanCode(@RequestParam("uid")String uid, @RequestParam("code")String code){
        String invalidCode = "InvalidCode";
        String codeExpired = "CodeExpired";
        String decodeCode = decodeCode(code);
        if(invalidCode.equals(decodeCode)){
            return new ResponseModel(142,"无法识别的二维码");
        }else if(codeExpired.equals(decodeCode)){
            return new ResponseModel(141,"二维码已过期");
        }

        int signInType =iSignInActivityService.selectSignInType(decodeCode);

        // 通过lid查找该学生当前的签到活动
        List<SignInRecord> record = iSignInActivityService.selectContentBylid(uid, decodeCode);

        // 验证是否有签到活动记录
        if (record == null || record.isEmpty()) {
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("decodeCode", decodeCode);
            responseData.put("records", new Object[0]); // 返回空数组
            return new ResponseModel(200, "没有签到记录", responseData, -1);
        }

        // 如果 record 不为空，继续处理
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("decodeCode", decodeCode);
        responseData.put("records", record.toArray());

        if(signInType==0 ||signInType==1 ||signInType==2 ){
            return new ResponseModel(200,"扫描二维码成功",responseData,signInType);

        }
        return new ResponseModel(200,"扫描二维码成功",decodeCode);
    }

    @CurrentLimiter(QPS=5)
    @RequestMapping(value = "/selectActivityByMonth",method = RequestMethod.GET)
    public  ResponseModel selectActivityByMonth(@RequestParam("tid")String tid, @RequestParam("month")String month){
        try{
            List<Integer> outDays = new ArrayList<>();
            List<SignInActivity> days = iSignInActivityService.selectActivityByMonth(tid,month);
            Iterator iterator = days.iterator();
            int day;
            SignInActivity signInActivity;
            while (iterator.hasNext()){
                signInActivity = (SignInActivity)iterator.next();
                day = Integer.parseInt(signInActivity.getCreateTime().substring(8,10));
                if(!outDays.contains(day)) {
                    outDays.add(day);
                }
            }
            return new ResponseModel(200,"获取成功",outDays);
        }catch (Exception e){
            log.log(Level.SEVERE,"Error parsing date",e);
            return new ResponseModel(139,"获取失败");
        }
    }

    @RequestMapping(value = "/selectList",method = RequestMethod.GET)
    public void selectList(HttpServletResponse resp,
                           @RequestParam(value = "tid")String tid,
                           @RequestParam(value = "pageNum", required = false ,defaultValue = "1") int pageNum,
                           @RequestParam(value = "pageSize", required = false ,defaultValue = "10") int pageSize){
        try {
            List<Map<String,Object>> mapList=iSignInActivityService.selectList(tid);
            try {
                if(iSignInActivityService.isgroup(tid)==null||iSignInActivityService.isopen(tid)==1){
                    JSONObject jsonObject = PageUtil.wrap2(mapList,"Activity",pageSize,pageNum);
                    resp.setCharacterEncoding("utf-8");
                    /*得到输出流*/
                    PrintWriter respWriter = resp.getWriter();
                    System.out.println(mapList);
                    /*将JSON格式的对象toString()后发送*/
//                if(mapList!=null&&!mapList.isEmpty()){
                    respWriter.append(jsonObject.toString());
                }else{
                    resp.setCharacterEncoding("utf-8");
                    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); // 设置状态码为400，表示客户端错误
                    resp.setContentType("text/plain"); // 设置内容类型为纯文本
                    PrintWriter respWriter = resp.getWriter();
                    respWriter.append("查找失败或者组织管理者关闭考勤开放");
                }
            } catch (Exception e) {
                log.log(Level.SEVERE,"Error parsing date",e);
            }
        }catch (Exception e){
            log.log(Level.SEVERE,"Error parsing date",e);
        }
    }
    @RequestMapping(value = "/selectList1",method = RequestMethod.GET)
    public void selectList1(HttpServletResponse resp,
                            @RequestParam(value = "begindate",required = false)@DateTimeFormat(pattern = "yyyy-MM-dd")Date begindate,
                            @RequestParam(value = "enddate",required = false)@DateTimeFormat(pattern = "yyyy-MM-dd")Date enddate,
                            @RequestParam(value = "tid")String tid){
        try {
            List<Map<String,Object>> mapList=iSignInActivityService.selectList1(tid, LocalDateTime.ofInstant(begindate.toInstant(), ZoneId.systemDefault()),LocalDateTime.ofInstant(enddate.toInstant(), ZoneId.systemDefault()));
            try {
                int cishu=0;
                int total=0;
                int qiandao=0;
                int qingjia=0;
                int chidao=0;
                int qita=0;
                int weirenzheng=0;
                int kuangke=0;
                JSONObject jsonObject=new JSONObject();
                System.out.println(mapList);
                for(Map<String,Object> map:mapList){
                    String actid=map.get("actid").toString();
                    List<SignInLink> signInLinks=iSignInActivityService.selectLinkList(actid);
                    for(SignInLink signInLink:signInLinks){
                        String lid=signInLink.getLid();
                        SigninclassEntity signinclassEntity = signInClassService.selectClassbylid(lid);
                        if (signinclassEntity != null) {
                            cishu++;
                            total+=signinclassEntity.getNumber();
                            qiandao+=iSignInRecordService.selectRecCount1(lid,1);
                            chidao+=iSignInRecordService.selectRecCount1(lid,2);
                            qingjia+=iSignInRecordService.selectRecCount1(lid,3);
                            qita+=iSignInRecordService.selectRecCount1(lid,4);
                            weirenzheng+=iSignInRecordService.selectRecCount1(lid,5);
                            kuangke+=iSignInRecordService.selectRecCount1(lid,6);
                        }
                    }
                }
                jsonObject.put("cishu",cishu);
                jsonObject.put("total",total);
                jsonObject.put("qiandao",qiandao);
                jsonObject.put("chidao",chidao);
                jsonObject.put("qingjia",qingjia);
                jsonObject.put("qita",qita);
                jsonObject.put("weirenzheng",weirenzheng);
                jsonObject.put("kuangke",kuangke);
                /*将JSON格式的对象toString()后发送*/
//                if(mapList!=null&&!mapList.isEmpty()){
                resp.setCharacterEncoding("utf-8");
                /*得到输出流*/
                PrintWriter respWritter = resp.getWriter();
                /*将JSON格式的对象toString()后发送*/
                respWritter.append(jsonObject.toString());
//                }else{
//                    System.out.println("列表为空");
//                    respWriter.append("查找失败或者组织管理者关闭考勤开放");
//                }
            } catch (Exception e) {
                log.log(Level.SEVERE,"Error parsing date",e);
            }
        }catch (Exception e){
            log.log(Level.SEVERE,"Error parsing date",e);
        }
    }
    @RequestMapping(value = "/selectlinktype",method = RequestMethod.GET)
    public void selectlinktype(HttpServletResponse resp, @RequestParam(value = "lid")String lid){
        try {
            SignInLink signInLink=iSignInActivityService.selectLinkByLid(lid);
            SignInActivity signInActivity=iSignInActivityService.selectAct(lid);
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("linktype",signInLink.getLinkType());
            jsonObject.put("sign_stop_type",signInActivity.getSignStopType());
            try {
                resp.setCharacterEncoding("utf-8");
                /*得到输出流*/
                PrintWriter respWritter = resp.getWriter();
                /*将JSON格式的对象toString()后发送*/
                respWritter.append(jsonObject.toString());
            } catch (Exception e) {
                log.log(Level.SEVERE,"Error parsing date",e);
            }
        }catch (Exception e){
            log.log(Level.SEVERE,"Error parsing date",e);
        }
    }

    @RequestMapping(value = "/linkList",method = RequestMethod.GET)
    public void selectLinkList(HttpServletResponse resp, @RequestParam(value = "actid")String actid,
                               @RequestParam(value = "pageNum", required = false ,defaultValue = "1") int pageNum,
                               @RequestParam(value = "pageSize", required = false ,defaultValue = "10") int pageSize){
        try {
            QueryWrapper<SigninactivityEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("actid",actid);
            SigninactivityEntity signinactivityEntity = signinactivityMapper.selectOne(queryWrapper);
            int signStopType = -1;
            if(signinactivityEntity.getSignStopType() != null)
                signStopType = signinactivityEntity.getSignStopType();
            List<SignInLink> signInLinks=iSignInActivityService.selectLinkList(actid);
            ChangeDate changeDate = new ChangeDate();
            Date date = new Date(System.currentTimeMillis());
            for (SignInLink signInLink : signInLinks) {
                changeDate.setSettime(signInLink.getEndTime());
                if (signInLink.getEndTime() !=null && !signInLink.getEndTime().equals("") && date.after(changeDate.settime) && !signInLink.getEndTime().equals(signInLink.getStartTime())) {
                    signInLink.setStatus(2);
                }
            }
            try {
                JSONObject jsonObject = PageUtil.wrap3(signInLinks,"Link",pageSize,pageNum);
                jsonObject.put("signStopType",signStopType);
                resp.setCharacterEncoding("utf-8");
                /*得到输出流*/
                PrintWriter respWriter = resp.getWriter();
                /*将JSON格式的对象toString()后发送*/
                respWriter.append(jsonObject.toString());
            } catch (Exception e) {
                log.log(Level.SEVERE,"Error parsing date",e);
            }
        }catch (Exception e){
            log.log(Level.SEVERE,"Error parsing date",e);
        }
    }


    @ApiOperation("更新签到时限")
    @PostMapping("/updateLinkDuration")
    public ResponseModel updateLinkDuration(@RequestParam String lid,
                                            @RequestParam int duration) {

        if (iSignInActivityService.updateLinkDuration(lid, duration))
            return new ResponseModel(200, "操作成功");
        return new ResponseModel(500, "操作失败");
    }

    @ApiOperation("新增一次签到环节【rangement没有就传0】")
    @PostMapping("/addNewLink")
    public ResponseModel addNewLink(@RequestBody AddSigninLinkParam addSigninLinkParam) {

        if (iSignInActivityService.addOneNewLink(addSigninLinkParam))
            return new ResponseModel(200, "操作成功");
        return new ResponseModel(500, "操作失败");
    }


    @ApiOperation("获取随机签到码")
    @GetMapping("/getCode")
    public ResponseModel generateCode(@RequestParam String lid) {

        try {
            Object object = redisTemplate.opsForValue().get(lid + "-code");
            if (object != null)
                return new ResponseModel(200, object);
            return new ResponseModel(500, "该签到尚未激活！");
        }catch (Exception e){
            return new ResponseModel(500, "操作失败");
        }
    }

    @ApiOperation("用户点确定后就签到成功")
    @GetMapping("/verifyCode")
    public ResponseModel verifyCode(@RequestParam("lid") String lid,@RequestParam("code") String code){
        //return new ResponseModel(200,"签到成功");
         try{
            Object object = redisTemplate.opsForValue().get(lid + "-code");
            if( object == null ){
                return new ResponseModel(500 , "签到码不存在或已失效");
            }
            if(code.equals(object.toString())){
                return new ResponseModel(200,"校验成功");
            }else {
                return new ResponseModel(500,"校验失败");
            }
        }catch (Exception e){
            return new ResponseModel(500,"操作失败");
        }
    }
//    @ApiOperation("校验随机签到码")暂时无法使用
//    @GetMapping("/verifyCode1")
//    public ResponseModel verifyCode1(@RequestParam("lid") String lid, @RequestParam("code") String code) {
//        try {
//            String message = lid + ":" + code;
//            Object response = rabbitTemplate.convertSendAndReceive(RabbitEnum.verify_code.getExchange(), RabbitEnum.verify_code.getRouteKey(), message);
//
//            if (response == null) {
//                return new ResponseModel(500, "校验失败!!!!!!");
//            }
//
//            boolean isVerified = Boolean.parseBoolean(response.toString());
//            if (isVerified) {
//                return new ResponseModel(200, "校验成功");
//            } else {
//                return new ResponseModel(500, "校验失败11111");
//            }
//        } catch (Exception e) {
//            return new ResponseModel(500, "操作失败");
//        }
//    }

    @RequestMapping(value = "/selectAllList",method = RequestMethod.GET)
    @CurrentLimiter(QPS=5)
    public  ResponseModel selectAllList(@RequestParam("tid")String tid){
        try{
            List<SignInActivity> activities = iSignInActivityService.selectAllList(tid);

            return new ResponseModel(200,"获取成功",activities);
        }catch (Exception e){
            log.log(Level.SEVERE,"Error parsing date",e);
            return new ResponseModel(139,"获取失败");
        }
    }
}